package twelve.dynamicCompile;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;

public class TestDynamicCompile {
    public static void main(String[] args) throws Exception {
        String path = "D:/IdeaProjects/JavaSEProject/src/";
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int result = compiler.run(null, null, null,
                path + "classloader/HelloWorld.java");
        System.out.println(result == 0 ? "编译成功" : "编译失败");

        Runtime run = Runtime.getRuntime();
        Process process = run.exec("java -cp " + path + " HelloWorld");

        InputStream in = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String info = "";
        while ((info = reader.readLine()) != null) {
            System.out.println(info);
        }

        try{
            URL[] urls = new URL[]{new URL("file:/" + path)};
            URLClassLoader loader = new URLClassLoader(urls);
            Class c = loader.loadClass("classloader.HelloWorld");
            c.getMethod("main", String[].class).invoke(null, (Object) new String[]{});
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
